import _ from 'lodash';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';

import Seo from '@/core/components/Seo';
import { getIdFromSlug, getNameFromSlug } from '@/core/utils/slug';
import Breadcrumb from '@/lib/category/components/Breadcrumb';
import { useEffect, useState } from 'react';
import odooApi from '@/core/api/odooApi';

const BasicLayout = dynamic(() =>
  import('@/core/components/layouts/BasicLayout')
);
const ProductSearch = dynamic(() =>
  import('@/lib/product/components/ProductSearch')
);
const CategorySection = dynamic(() =>
  import('@/lib/product/components/CategorySection')
);

export default function CategoryDetail() {
  const router = useRouter();
  const { slug = '', page = 1 } = router.query;
  const [dataCategories, setDataCategories] = useState([]);

  const [shortDesc, setShortDesc] = useState('');
  const categoryName = getNameFromSlug(slug);
  const categoryId = getIdFromSlug(slug);
  const q = router?.query.q || null;
  const query = {
    fq: `category_id_i:${categoryId}`,
    page,
  };
  if (q) {
    query.q = q;
  }
  useEffect(() => {
    if (!router.isReady) return;
    if (!categoryId) return;

    const loadShortDesc = async () => {
      const res = await odooApi(
        'GET',
        `/api/v1/category/${categoryId}/short-desc`
      );

      const desc = res?.shortDesc || '';
      setShortDesc(desc);
    };

    loadShortDesc();
  }, [router.isReady, categoryId]);

  return (
    <BasicLayout>
      <Seo
        title={`Beli ${categoryName} di Indoteknik`}
        description={`Jual ${categoryName} Kirim Jakarta Surabaya Semarang Makassar Manado Denpasar Balikpapan Medan Palembang Lampung Bali Bandung Makassar Manado.`}
        additionalMetaTags={[
          {
            property: 'keywords',
            content: `Jual ${categoryName}, harga ${categoryName}, ${categoryName} murah, toko ${categoryName}, ${categoryName} jakarta, ${categoryName} surabaya`,
          },
        ]}
      />

      <Breadcrumb categoryId={categoryId} shortDesc={shortDesc} />

      {!_.isEmpty(router.query) && (
        <ProductSearch
          query={query}
          categories={categoryId}
          prefixUrl={`/shop/category/${slug}`}
        />
      )}
    </BasicLayout>
  );
}
